<template>
  <div class="travel-map-container">
    <div id="map-container" class="map-area"></div>
    <div class="map-controls">
      <div class="control-panel">
        <button class="map-btn zoom-in" @click="zoomIn">+</button>
        <button class="map-btn zoom-out" @click="zoomOut">-</button>
      </div>
      <div class="legend" v-if="hasRoute && showMarkers">
        <div class="legend-item">
          <span class="legend-marker attraction"></span>
          <span class="legend-text">景点</span>
        </div>
        <div class="legend-item">
          <span class="legend-marker route"></span>
          <span class="legend-text">推荐路线</span>
        </div>
      </div>
    </div>
    
    <!-- 保存按钮 -->
    <div class="save-button-container">
      <button class="save-button" @click="saveAndShowMarkers" v-if="!showMarkers && travelRoute">
        <i class="fas fa-save"></i> 保存并显示路线
      </button>
      <div class="save-success" v-if="showMarkers && saveSuccess">
        <i class="fas fa-check-circle"></i> 已保存路线
      </div>
    </div>
    
    <!-- 行程天数指示器 -->
    <div class="day-indicators" v-if="travelRoute && showMarkers">
      <div 
        v-for="(day, index) in travelDays" 
        :key="day"
        class="day-indicator"
        :class="{ 'active': activeDay === index }"
        @click="setActiveDay(index)"
      >
        {{ day }}
      </div>
    </div>
    
    <!-- 路线信息展示 -->
    <div class="route-info" v-if="travelRoute && activeDay !== null && showMarkers">
      <div class="route-info-header">
        <h3>{{ travelRoute.itinerary[activeDay].theme }}</h3>
        <span class="day-label">{{ travelRoute.itinerary[activeDay].day }}</span>
      </div>
      <div class="route-info-content">
        <div 
          v-for="(event, index) in travelRoute.itinerary[activeDay].events" 
          :key="index"
          class="event-item"
        >
          <div class="event-time">{{ event.time }}</div>
          <div class="event-content">
            <div class="event-title">{{ event.activity }}</div>
            <div class="event-details" v-if="event.details">
              <div v-if="event.details.highlights">{{ event.details.highlights }}</div>
              <div v-if="event.details.features">{{ event.details.features }}</div>
              <div v-if="event.details.essence">{{ event.details.essence }}</div>
              <div v-if="event.details.history">{{ event.details.history }}</div>
              <div v-if="event.details.transportation" class="transportation">
                <span class="transport-icon">🚇</span> {{ event.details.transportation }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useAiRouteStore } from '@/stores/aiRouteStore';

const routeStore = useAiRouteStore();
const currentRoute = computed(() => routeStore.currentRoute);
const hasRoute = computed(() => currentRoute.value.length > 0);

const mapInstance = ref(null);
const markerList = ref([]);
const polyline = ref(null);
const mapLoaded = ref(false);

// 新增：控制是否显示标注点
const showMarkers = ref(false);
const saveSuccess = ref(false);

// 新增：保存并显示标注点的方法
const saveAndShowMarkers = () => {
  showMarkers.value = true;
  saveSuccess.value = true;
  
  // 3秒后隐藏保存成功提示
  setTimeout(() => {
    saveSuccess.value = false;
  }, 3000);
  
  // 如果地图已加载且有路线，立即显示标注点
  if (mapLoaded.value && travelRoute.value) {
    renderMapMarkers();
  }
};

// 存储旅游路线数据
const travelRoute = ref(null);
const activeDay = ref(null);
const travelDays = computed(() => {
  if (!travelRoute.value) return [];
  return travelRoute.value.itinerary.map(day => day.day);
});

// 景点地理位置数据库
const attractionsDatabase = {
  // 已有的景点
  '故宫博物院': { lng: 116.397, lat: 39.918, description: '中国明清两代的皇家宫殿，世界上现存规模最大、保存最完整的木质结构古建筑之一' },
  '天安门广场': { lng: 116.404, lat: 39.909, description: '世界上最大的城市中心广场，可容纳一百万人举行盛大集会' },
  '颐和园': { lng: 116.267, lat: 39.999, description: '中国现存规模最大、保存最完整的皇家园林，被誉为"皇家园林博物馆"' },
  '八达岭长城': { lng: 116.024, lat: 40.362, description: '中国古代的伟大防御工程，八达岭长城是最受欢迎的旅游段落' },
  '天坛': { lng: 116.407, lat: 39.882, description: '明清两代皇帝祭天、祈求五谷丰登的场所，是世界上最大的古代祭祀建筑群' },
  '恭王府': { lng: 116.380, lat: 39.934, description: '清代规模最大的王府之一，曾是和珅、恭亲王奕訢的府邸' },
  '什刹海': { lng: 116.380, lat: 39.940, description: '历史悠久的风景区，由前海、后海和西海组成，是老北京风貌的代表地区' },
  '圆明园': { lng: 116.298, lat: 40.008, description: '清代大型皇家园林，被称为"万园之园"，1860年被英法联军焚毁' },
  '北海公园': { lng: 116.383, lat: 39.926, description: '中国现存最古老、最完整、最具代表性的皇家园林之一，始建于辽代' },
  '鸟巢(国家体育场)': { lng: 116.397, lat: 39.993, description: '2008年北京奥运会的主会场，因外形酷似鸟巢而得名' },
  '水立方(国家游泳中心)': { lng: 116.390, lat: 39.992, description: '2008年北京奥运会游泳比赛场馆，外观酷似水分子结构' },
  '798艺术区': { lng: 116.495, lat: 39.984, description: '建于1950年代的原国营798厂等电子工业的老厂区改建而成的当代艺术中心' },
  '南锣鼓巷': { lng: 116.403, lat: 39.936, description: '北京最古老的街区之一，保留了老北京胡同的风貌' },
  '王府井': { lng: 116.418, lat: 39.914, description: '北京最著名、最繁华的商业街之一，有数百年历史' },
  '景山公园': { lng: 116.397, lat: 39.928, description: '位于故宫北面的皇家园林，是俯瞰北京城全景的最佳地点之一' },
  
  // 新增的景点
  '首都机场': { lng: 116.597, lat: 40.080, description: '北京首都国际机场，中国最大的民用航空港之一' },
  '奥林匹克森林公园': { lng: 116.390, lat: 40.020, description: '亚洲最大城中绿肺，夏季荷花遍野，北京奥运会配套设施' },
  '北京动物园': { lng: 116.339, lat: 39.940, description: '拥有大熊猫馆和热带雨林馆，是北京最受欢迎的动物园' },
  '十三陵水库': { lng: 116.244, lat: 40.260, description: '明十三陵附近的大型水库，景色优美，适合骑行' },
  '北京植物园': { lng: 116.206, lat: 39.996, description: '收集保存了3000多种植物，是北京重要的科研和旅游胜地' },
  '香山公园': { lng: 116.184, lat: 39.996, description: '以红叶闻名，春季山桃花溪，秋季红叶岭景色绝佳' },
  '慕田峪长城': { lng: 116.569, lat: 40.429, description: '长城最精华的一段，人少景美，有"世界七大奇迹"之一的美誉' },
  '朝阳公园': { lng: 116.483, lat: 39.933, description: '北京市区最大的综合性公园之一，免费开放，可租船/骑行' },
  '前门大街': { lng: 116.395, lat: 39.899, description: '北京最古老的商业街之一，保留了清末民初的建筑风格' }
};

onMounted(() => {
  // 动态引入百度地图脚本
  const script = document.createElement('script');
  script.src = 'https://api.map.baidu.com/api?v=3.0&ak=DpbJ4hDkZSlBHunZMkVrQ2h0cRrwfpr0&callback=initBMap';
  document.head.appendChild(script);
  
  // 初始化地图的回调函数
  window.initBMap = function() {
    initMap();
    loadMockData();
  };
});

// 修改初始化地图函数
const initMap = () => {
  const map = new BMap.Map('map-container');
  const point = new BMap.Point(116.404, 39.915); // 北京中心点
  map.centerAndZoom(point, 12);
  map.enableScrollWheelZoom(true);
  map.addControl(new BMap.NavigationControl());
  map.addControl(new BMap.ScaleControl());
  
  mapInstance.value = map;
  mapLoaded.value = true;
  
  // 只有当showMarkers为true时才渲染标记点
  if (showMarkers.value && travelRoute.value) {
    renderMapMarkers();
  }
};

// 新增：从模拟数据加载路线
const loadMockData = () => {
  // 模拟从后端获取数据
  const mockRouteData = {
    "overview": {
      "arrivalAirport": "北京首都国际机场（PEK）",
      "departureAirport": "北京首都国际机场（PEK）",
      "tripDuration": "7天6夜",
      "policy": "适用俄罗斯公民240小时免签政策",
      "transportation": "地铁 + 公交 + 共享单车",
      "transportationCost": "约150元"
    },
    "itinerary": [
      {
        "day": "第1天",
        "theme": "城市绿肺探索",
        "events": [
          {
            "time": "08:30-09:30",
            "activity": "抵达首都机场",
            "details": {
              "transportation": "航班落地",
              "highlights": "办理入境手续，兑换人民币",
              "tip": "建议在机场兑换少量现金，其余使用移动支付"
            }
          },
          {
            "time": "09:30-10:30",
            "activity": "前往市区",
            "details": {
              "transportation": "机场快轨",
              "features": "乘坐机场快轨前往三元桥站，换乘地铁",
              "cost": "约25元/人"
            }
          },
          {
            "time": "10:30-11:00",
            "activity": "酒店办理入住",
            "details": {
              "highlights": "行李寄存（如无法立即入住）",
              "tip": "请务必保管好护照等证件"
            }
          },
          {
            "time": "11:00-13:00",
            "activity": "奥林匹克公园",
            "details": {
              "highlights": "鸟巢和水立方外观参观",
              "transportation": "地铁8号线「奥林匹克公园站」",
              "features": "著名的2008年北京奥运会场馆",
              "tip": "可以花30元登上奥林匹克塔，俯瞰整个奥林匹克公园"
            }
          },
          {
            "time": "13:00-14:00",
            "activity": "午餐",
            "details": {
              "dining": "奥林匹克公园附近的小吃街",
              "features": "品尝北京特色小吃",
              "recommendation": "品尝老北京炸酱面、豆汁或卤煮"
            }
          },
          {
            "time": "14:00-16:30",
            "activity": "奥林匹克森林公园",
            "details": {
              "highlights": "亚洲最大城中绿肺，夏季荷花遍野",
              "transportation": "步行10分钟即可到达",
              "features": "宁静的湖泊、茂密的森林和各类运动设施",
              "activities": "划船、骑车、徒步都是不错的选择",
              "tip": "下午可租自行车环湖骑行，费用约20元/小时"
            }
          },
          {
            "time": "17:00-19:00",
            "activity": "北京动物园",
            "details": {
              "features": "大熊猫馆+热带雨林馆（室内避暑）",
              "dining": "园内「熊猫咖啡厅」推荐熊猫造型甜品",
              "highlight": "中国本土珍稀动物展区",
              "transportation": "地铁4号线「动物园站」",
              "tip": "傍晚动物活动较多，游客较少"
            }
          },
          {
            "time": "19:30-21:00",
            "activity": "晚餐与休息",
            "details": {
              "dining": "三里屯太古里美食广场",
              "transportation": "地铁10号线「三里屯站」",
              "features": "国际化餐饮体验",
              "tip": "此处也是北京著名的夜生活区域，可以感受现代北京的夜景"
            }
          }
        ]
      },
      {
        "day": "第2天",
        "theme": "皇家园林之旅",
        "events": [
          {
            "time": "08:30-12:00",
            "activity": "颐和园",
            "details": {
              "essence": "昆明湖划船+万寿山登高（建议租电瓶车）",
              "transportation": "地铁4号线「北宫门站」"
            }
          },
          {
            "time": "14:00-17:00",
            "activity": "圆明园",
            "details": {
              "history": "西洋楼遗址的荷花景观（6-8月最佳）",
              "tip": "租借智能导览耳机了解遗址故事"
            }
          }
        ]
      },
      {
        "day": "第3天",
        "theme": "山峦长城穿越",
        "events": [
          {
            "time": "07:30-12:00",
            "activity": "八达岭长城",
            "details": {
              "highlights": "乘景区小火车「水关段」登顶（减少体力消耗）",
              "tip": "夏季紫外线强，建议携带登山杖"
            }
          },
          {
            "time": "14:00-17:00",
            "activity": "十三陵水库",
            "details": {
              "features": "骑行环湖（景区提供自行车租赁）",
              "tip": "下午4点逆光拍摄水面最佳"
            }
          }
        ]
      },
      {
        "day": "第4天",
        "theme": "生态秘境",
        "events": [
          {
            "time": "09:00-16:00",
            "activity": "北京植物园+香山公园（联票游览）",
            "details": {
              "highlights": "春季山桃花溪（4月）、秋季红叶岭（10月）",
              "transportation": "地铁10号线转公交634路"
            }
          }
        ]
      },
      {
        "day": "第5天",
        "theme": "泃河流域探秘",
        "events": [
          {
            "time": "08:00-17:00",
            "activity": "慕田峪长城",
            "details": {
              "features": "人少景美，可选「西线野长城」徒步",
              "transportation": "公交916快+景区接驳车（全程约2小时）"
            }
          }
        ]
      },
      {
        "day": "第6天",
        "theme": "城市休闲日",
        "events": [
          {
            "time": "09:00-12:00",
            "activity": "朝阳公园",
            "details": {
              "features": "免费开放，可租船/骑行"
            }
          },
          {
            "time": "14:00-17:00",
            "activity": "798艺术区",
            "details": {
              "essence": "从自然景观到现代艺术体验的转换"
            }
          }
        ]
      },
      {
        "day": "第7天",
        "theme": "离境日",
        "events": [
          {
            "time": "10:00-12:00",
            "activity": "前门大街",
            "details": {
              "features": "最后购物：同仁堂（特产）、全聚德（打包带走）"
            }
          },
          {
            "time": "14:00",
            "activity": "返回首都机场",
            "details": {
              "transportation": "按航班时间"
            }
          }
        ]
      }
    ],
    "tips": {
      "visaValidity": "请在入境第7日18:00前离境",
      "weatherPreparation": "当前北京22°C晴朗，建议携带防晒霜+轻便外套",
      "transportTips": "下载「Metro大都会」APP可扫码乘坐所有公共交通",
      "emergencyContact": "+86-10-12301（北京旅游咨询热线）",
      "remarks": "需要中英双语版或调整景点顺序请随时告知！"
    }
  };
  
  travelRoute.value = mockRouteData;
  activeDay.value = 0; // 默认选择第一天
};

// 修改：设置活动日期
const setActiveDay = (index) => {
  activeDay.value = index;
  
  // 如果地图已加载且显示标记点，则更新地图上的标记点
  if (mapLoaded.value && showMarkers.value) {
    clearMapMarkers();
    renderMapMarkers();
  }
};

// 修改：渲染地图标记点的方法
const renderMapMarkers = () => {
  if (!mapInstance.value || !travelRoute.value || activeDay.value === null) return;
  
  // 清除现有的标记点和路线
  clearMapMarkers();
  
  const dayEvents = travelRoute.value.itinerary[activeDay.value].events;
  const points = [];
  
  // 为每个事件创建标记点
  dayEvents.forEach((event, index) => {
    const attractionName = extractAttractionName(event.activity);
    if (attractionName && attractionsDatabase[attractionName]) {
      const location = attractionsDatabase[attractionName];
      const point = new BMap.Point(location.lng, location.lat);
      points.push(point);
      
      // 创建标记点
      const marker = new BMap.Marker(point);
      mapInstance.value.addOverlay(marker);
      markerList.value.push(marker);
      
      // 创建信息窗口
      const infoWindow = new BMap.InfoWindow(`
        <div class="marker-info">
          <h4>${attractionName}</h4>
          <p>${location.description}</p>
          <div class="event-time">${event.time}</div>
        </div>
      `);
      
      // 点击标记点时显示信息窗口
      marker.addEventListener('click', function() {
        this.openInfoWindow(infoWindow);
      });
      
      // 如果是第一个点，将地图中心设为该点
      if (index === 0) {
        mapInstance.value.centerAndZoom(point, 13);
      }
    }
  });
  
  // 如果有多个点，绘制路线
  if (points.length > 1) {
    const polylineObj = new BMap.Polyline(points, {
      strokeColor: '#16a34a',
      strokeWeight: 4,
      strokeOpacity: 0.7
    });
    mapInstance.value.addOverlay(polylineObj);
    polyline.value = polylineObj;
  }
};

// 清除地图上的标记点和路线
const clearMapMarkers = () => {
  if (!mapInstance.value) return;
  
  // 清除标记点
  markerList.value.forEach(marker => {
    mapInstance.value.removeOverlay(marker);
  });
  markerList.value = [];
  
  // 清除路线
  if (polyline.value) {
    mapInstance.value.removeOverlay(polyline.value);
    polyline.value = null;
  }
};

// 从活动名称中提取景点名称
const extractAttractionName = (activity) => {
  for (const name in attractionsDatabase) {
    if (activity.includes(name)) {
      return name;
    }
  }
  return null;
};

// 放大地图
const zoomIn = () => {
  if (mapInstance.value) {
    const zoom = mapInstance.value.getZoom();
    mapInstance.value.setZoom(zoom + 1);
  }
};

// 缩小地图
const zoomOut = () => {
  if (mapInstance.value) {
    const zoom = mapInstance.value.getZoom();
    mapInstance.value.setZoom(zoom - 1);
  }
};
</script>

<style scoped>
.travel-map-container {
  position: relative;
  width: 100%;
  height: 600px;
  margin: 20px 0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.map-area {
  width: 100%;
  height: 100%;
}

.map-controls {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 10;
}

.control-panel {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.map-btn {
  width: 36px;
  height: 36px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.map-btn:hover {
  background-color: #f5f5f5;
}

.legend {
  background-color: white;
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.legend-item:last-child {
  margin-bottom: 0;
}

.legend-marker {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  border-radius: 50%;
}

.legend-marker.attraction {
  background-color: #16a34a;
}

.legend-marker.route {
  width: 16px;
  height: 4px;
  border-radius: 2px;
  background-color: #16a34a;
}

.legend-text {
  font-size: 14px;
  color: #333;
}

.day-indicators {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  background-color: white;
  border-radius: 30px;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
  max-width: 90%;
  overflow-x: auto;
  scrollbar-width: thin;
}

.day-indicators::-webkit-scrollbar {
  height: 4px;
}

.day-indicators::-webkit-scrollbar-thumb {
  background-color: rgba(22, 163, 74, 0.5);
  border-radius: 4px;
}

.day-indicator {
  padding: 10px 24px;
  border-radius: 20px;
  font-size: 15px;
  min-width: 100px;
  text-align: center;
  white-space: nowrap;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0 4px;
}

.day-indicator:hover {
  background-color: #f0fdf4;
}

.day-indicator.active {
  background-color: #16a34a;
  color: white;
  font-weight: 500;
}

.route-info {
  position: absolute;
  top: 80px;
  right: 20px;
  width: 300px;
  max-height: calc(100% - 100px);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  overflow-y: auto;
  z-index: 10;
}

.route-info-header {
  padding: 16px;
  background-color: #16a34a;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.route-info-header h3 {
  margin: 0;
  font-size: 18px;
}

.day-label {
  font-size: 14px;
  padding: 4px 8px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.route-info-content {
  padding: 16px;
}

.event-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.event-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.event-time {
  font-size: 14px;
  color: #16a34a;
  font-weight: 600;
  margin-bottom: 8px;
}

.event-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}

.event-details {
  font-size: 14px;
  color: #555;
  line-height: 1.5;
}

.transportation {
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.transport-icon {
  margin-right: 6px;
}

.marker-info {
  padding: 5px;
}

.marker-info h4 {
  margin: 0 0 5px 0;
  color: #16a34a;
}

.marker-info p {
  margin: 0 0 5px 0;
  font-size: 13px;
}

/* 新增：保存按钮样式 */
.save-button-container {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.save-button {
  background-color: #16a34a;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 16px;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(22, 163, 74, 0.3);
  transition: all 0.3s ease;
}

.save-button:hover {
  background-color: #15803d;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(22, 163, 74, 0.4);
}

.save-success {
  background-color: white;
  color: #16a34a;
  border-radius: 6px;
  padding: 10px 16px;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .route-info {
    width: calc(100% - 40px);
    top: auto;
    bottom: 70px;
    right: 20px;
    left: 20px;
    max-height: 200px;
  }
  
  .day-indicators {
    top: 70px;
    padding: 6px;
    max-width: 95%;
  }
  
  .day-indicator {
    padding: 8px 16px;
    min-width: 80px;
    font-size: 14px;
  }
  
  .save-button-container {
    top: 20px;
    right: 20px;
  }
}
</style> 